<template>
  <div class="sign-main-frame">
    <!--    顶栏-->
    <div class="seal-top">
      <div class="btn-return">
        <el-page-header icon="ArrowLeft" content="文件签署" @back="$router.push('/wel/index')"/>
      </div>
      <div class="btn-group" v-if="sealSignForm.signStatus !== 4">
        <el-row style="margin-top: 10px;">
          <el-col :span="12" v-show="store.getters.userInfo.username === sealSignForm.signSponsor && sealSignForm.signStatus === 3">
            <el-button type="danger" size="default" icon="RefreshLeft" @click="withdraw">
              撤回</el-button>
          </el-col>
          <el-col :span="12" v-show="(mySignStatus === 1 || mySignStatus === 2) && sealSignForm.signStatus === 3">
            <el-button type="primary" size="default" icon="Stamp" @click="generateSeal" v-if="activeName === 'first'">
              签署文件</el-button>
            <el-button type="primary" size="default" icon="Stamp" @click="generateSeal" v-else-if="activeName === 'second'">
              签署文件</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="btn-group" v-else-if="sealSignForm.signStatus === 4">
        <el-button type="info" size="default" icon="Download" @click="downloadPDF()">
          导出签署文件</el-button>
        <el-button type="info" plain size="default" icon="Grid" @click="QRbtn()">
          生成文件二维码</el-button>
        <!-- 分享展示, 预览的二维码的弹层  -->
        <el-dialog title="扫一扫 直接在手机上打开文件" v-model="showCodeDialog" width="310px" center>
          <qrcode-vue :value="sealSignForm.signFilePath" :size="size" level="H" style="margin: 0 auto"/>
        </el-dialog>
      </div>
    </div>

    <div class="seal-all">
      <!--    左侧文件信息-->
      <div class="seal-left">
        <div class="tabs">
          <div class="tabs-bar"><div class="tabs-title">任务信息</div><el-divider></el-divider></div>
          <div class="sa-tab-container">
            <div class="sign-flow-info">
              <div class="sign-flow-info-detail">
                <div class="detail-item">
                  <div class="detail-item-title">文件主题</div>
                  <div class="detail-item-desc wrap">{{sealSignForm.signName}}</div>
                </div>
                <div class="detail-item">
                  <div class="detail-item-title">文件名称</div>
                  <div class="detail-item-desc wrap">{{sealSignForm.signFileName}}</div>
                </div>
                <div class="detail-item">
                  <div class="detail-item-title">发起方</div>
                  <div class="detail-item-desc wrap">{{sealSignForm.signSponsor}}</div>
                </div>
                <div class="detail-item">
                  <div class="detail-item-title">发起时间</div>
                  <div class="detail-item-desc wrap">{{dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSignForm.signStartTime))}}</div>
                </div>
              </div>
              <div class="sign-right-receiver-wrapper">
                <div class="detail-item">
                  <div class="detail-item-title" style="margin-bottom: 8px;font-size: 14px">签署详情</div>
                  <div class="detail-item-title">签署方</div>
                  <div class="detail-item-desc wrap">{{sealSignForm.signParticipant}}</div>
                </div>
                <div class="detail-item">
                  <div class="detail-item-title">文件时间流</div>
                  <el-timeline style="padding: 0;margin: 16px 0 0 10px">
                    <el-timeline-item
                        v-for="(activity, index) in activities"
                        :key="index"
                        :timestamp="activity.timestamp"
                        icon="Position"
                        size="large"
                        color="#1063f1"
                    >
                      {{ activity.content }}
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      中间pdf内容预览-->
      <div
          class="seal-center"
          v-loading="leftLoading"
          element-loading-svg-view-box="-10, -10, 50, 50"
          element-loading-text="签署中，请稍等...">
        <div class="pdf-bg">
          <VuePdf
              v-if="!isShow && pdfShow"
              ref="wrapper"
              v-for="page1 in numOfPages"
              :key="page1"
              :page="page1"
              :src="sealSignForm.signFilePath"
              style="width:100%"
              :scale="1"/>

          <VuePdf
              v-else-if="isShow"
              ref="wrapper"
              v-for="page2 in numOfPages"
              :key="page2"
              :page="page2"
              :src="newPdfUrl"
              style="width:100%;"
              :scale="1"/>
        </div>
      </div>
      <!--      右侧印章展示-->
      <!--      任务未完成----待参与人查看-->
      <div class="seal-right" v-if="(sealSignForm.signParticipant.indexOf(store.getters.userInfo.username) !== -1) && mySignStatus !== 2 && sealSignForm.signStatus === 3">
        <div class="seal_title">
          <p>我的印章</p>
        </div>
        <el-tabs
            v-model="activeName"
            class="demo-tabs"
            v-loading="rightLoading"
            element-loading-svg-view-box="-10, -10, 50, 50"
            element-loading-text="加载中，请稍等...">
          <el-tab-pane label="我创建的" name="first">
            <div class="seal-item" v-for="item in sealForm" :key="item.sealId" >
              <div @click="choseSeal(item.sealId)">
                <div :class="item.sealId === sealChose ?'item-border__active':'item-border'">
                  <img :src="item.sealPath">
                  <div class="seal_name">
                    <p >{{ item.sealName }}</p>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="授权印章" name="second">
            <div class="seal-item" v-for="item in sealAuthForm" :key="item.sealId" >
              <div @click="choseSeal(item.sealId)">
                <div :class="item.sealId === sealChose ?'item-border__active':'item-border'">
                  <img :src="item.sealPath">
                  <div class="seal_name">
                    <p >{{ item.sealName }}</p>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!--      任务未完成----任务发起人查看-->
      <div class="seal-right" v-else-if="sealSignForm.signSponsor === store.getters.userInfo.username && sealSignForm.signStatus === 3">
        <div class="seal_title">
          <p>任务状态</p>
        </div>
        <el-divider></el-divider>
        <div class="seal-finish">
          <img src="../../img/doing.svg" style="width: 50px">
          <div style="margin-top: 10px">进行中...</div>
          <div style="margin-top: 10px">待{{notSigner.toString()}}签署</div>
        </div>
      </div>
      <!--      任务未完成----该查看人已完成-->
      <div class="seal-right" v-else-if="mySignStatus === 2 && sealSignForm.signStatus === 3">
        <div class="seal_title">
          <p>任务状态</p>
        </div>
        <el-divider></el-divider>
        <div class="seal-finish">
          <img src="../../img/doing.svg" style="width: 50px">
          <div style="margin-top: 10px">进行中...</div>
          <div style="margin-top: 10px">您已完成签署</div>
          <div style="margin-top: 10px">待{{notSigner.toString()}}签署</div>
        </div>
      </div>
      <!--      任务已完成----所有人查看-->
      <div class="seal-right" v-else-if="sealSignForm.signStatus === 4">
        <div class="seal_title">
          <p>任务状态</p>
        </div>
        <el-divider></el-divider>
        <div class="seal-finish">
          <img src="../../img/finish.svg" >
          <div style="margin-top: 10px">已完成</div>
        </div>
      </div>
      <!--      任务已撤回----所有人查看-->
      <div class="seal-right" v-else-if="sealSignForm.signStatus === 2">
        <div class="seal_title">
          <p>任务状态</p>
        </div>
        <el-divider></el-divider>
        <div class="seal-finish">
          <img src="../../img/withdraw.svg" style="width: 50px;">
          <div style="margin-top: 10px">已被{{sealSignForm.signSponsor}}撤回</div>
        </div>
      </div>
      <!--      任务已过期----所有人查看-->
      <div class="seal-right" v-else-if="sealSignForm.signStatus === 1">
        <div class="seal_title">
          <p>任务状态</p>
        </div>
        <el-divider></el-divider>
        <div class="seal-finish">
          <img src="../../img/timeout.svg" style="width: 50px;">
          <div style="margin-top: 10px">该任务已过期</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref,getCurrentInstance} from 'vue';
import {getAuthSealApi, getSealByCreaterApi, sealWatermarkApi} from '../../api/seal';
const {proxy} = getCurrentInstance()
import QrcodeVue from 'qrcode.vue'
import '../../css/Sign/seal_use.css'
import {getSealSignBySignIdApi, getSignFileApi, withdrawSignApi} from '../../api/sign';
import {validatenull} from '../../utils/validate';
import {ElMessage, ElMessageBox} from 'element-plus';
import {compareDate, dateFormat} from '../../utils/util';
import {useStore} from 'vuex';

const store = useStore()
const userId = store.getters.userId
const username = store.getters.userInfo.username

//二维码相关配置
const showCodeDialog = ref(false)
const size = ref(0)
const QRbtn = () => {
  showCodeDialog.value = true
  size.value = 256
}
const wrapper = ref(null)

const leftLoading = ref(false)
const rightLoading = ref(false)

// 时间线数组
const activities = ref([])

//接收传过来的路由信息
const signId = ref("")
signId.value = proxy.$route.query.signId

const pdfShow = ref(false)
const notSigner = ref([]) //未签署人数组

const mySignStatus = ref(0) //当前人的签署状态

/**
 * 获取文件签署信息
 */
const getSealSignBySignId = () => {
  getSealSignBySignIdApi(signId.value,userId)
      .then(res=>{
        let data = res.data.result
        sealSignForm.value = data
        pdfShow.value = true
        let signStartTime = dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSignForm.value.signStartTime))
        // ------------------------- 发起签署 时间线 -------------------------
        activities.value = []

        // 初始 发起人时间
        activities.value.unshift({
          content: sealSignForm.value.signSponsor+"发起签署",
          timestamp: signStartTime
        })

        // 操作时间数组
        const operateLine = ref([])
        notSigner.value = []
        let sealSigner = data.sealSigner;
        for(let i=0;i < sealSigner.length ; i++){
          if(!validatenull(sealSigner[i].signerViewTime)){
            operateLine.value.push({
              content: sealSigner[i].signerId + "已查看",
              timestamp: dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSigner[i].signerViewTime))
            })
          }
          if(!validatenull(sealSigner[i].signerSignTime)){
            operateLine.value.push({
              content: sealSigner[i].signerId + "已签署",
              timestamp: dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSigner[i].signerSignTime))
            })
          }

          // 该签署人未签署则放置于未签署人数组中
          if(sealSigner[i].signerSignStatus !== 2){
            notSigner.value.push(sealSigner[i].signerId)
          }

          if(sealSigner[i].signerId === username){
            mySignStatus.value = sealSigner[i].signerSignStatus
          }
        }

        // 对操作时间数组进行排序
        operateLine.value.sort(function(a, b) {
          return b.timestamp< a.timestamp? -1 : 1
        })

        // 将操作时间数组与时间线数组结合
        activities.value = operateLine.value.concat(activities.value)

        if(sealSignForm.value.signStatus === 4){
          activities.value.unshift({
            content: "该签署任务已完成",
            timestamp: dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSignForm.value.signEndTime))
          })
        } else if(sealSignForm.value.signStatus === 3){ //如果该任务未完成 显示谁未签署
          activities.value.unshift({
            content: "待" + notSigner.value.toString() + "进行签署",
            timestamp: "------"
          })
        }else if(sealSignForm.value.signStatus === 2){
          activities.value.unshift({
            content: "发起人" + sealSignForm.value.signSponsor + "撤回了文件",
            timestamp: dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSignForm.value.signEndTime))
          })
        }else if(sealSignForm.value.signStatus === 1){
          activities.value.unshift({
            content: "该文件已过期",
            timestamp: dateFormat("YYYY-mm-dd HH:MM:SS",new Date(sealSignForm.value.signDeadline))
          })
        }
      }).catch(res=>{
    ElMessage.error(res)
  })
}
getSealSignBySignId()

const activeName = ref("first")

const numOfPages = ref(20)

/**
 * 签署任务信息表单
 */
const sealSignForm = ref({
  signName: "",
  signSponsor: '',
  signStartTime: '',
  signSignTime: '',
  signEndTime: '',
  signStatus: '',
  signTemplateSealId: "",
  signParticipant: "",
  signFilePath: '',
  signFileName: ''
})


const sealChose = ref("")

const choseSeal = (sealId) => {
  sealChose.value = sealId
}

/**
 * 获取我创建的印章数据
 */
const sealForm = ref({
  sealId: '',
  sealName: "",
  sealPath:"",
})

const getSealByCreater = () => {
  rightLoading.value = true
  getSealByCreaterApi(userId,1,100).then(res=>{
    let data = res.data.result
    sealForm.value = data
    rightLoading.value = false
  })
}
getSealByCreater()

/**
 * 获取被授权的印章数据
 */
const sealAuthForm = ref({
  sealId: '',
  sealName: "",
  sealPath:"",
})

const getSealAuth = () => {
  rightLoading.value = true
  getAuthSealApi(1,100,userId).then(res=>{
    let data = res.data.result
    // 筛选出已过期的印章
    sealAuthForm.value = data.filter((currentValue) =>{
      return compareDate(new Date(currentValue.sealAuth.authEndTime),new Date())
    })
    //sealAuthForm.value = data
    rightLoading.value = false
  })
}
getSealAuth()


const isShow = ref(false)
const newPdfUrl = ref("")

/**
 * 生成带水印的电子印章并签署到文件上
 */
const generateSeal = () => {
  if(validatenull(sealChose.value)){
    ElMessage.error("请选择一个印章进行签署！")
    return false
  }
  ElMessageBox.confirm(
      '确认使用该印章签署文件吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        sealSignForm.value.signTemplateSealId = sealChose.value  //绑定选择的印章
        sealSignForm.value.signParticipant = username //绑定当前签署人
        isShow.value = false
        leftLoading.value = true
        sealWatermarkApi(sealSignForm.value)
            .then(res=>{
              let data = res.data.result
              getSignFileApi(sealSignForm.value.signFilePath,data)
                  .then(res=>{
                    newPdfUrl.value = res.data.result
                    isShow.value = true
                    getSealSignBySignId()
                    sealSignForm.signStatus = 4
                    leftLoading.value = false
                  })
            }).catch(error=>{
          ElMessage.error(error)
          leftLoading.value = false
        })
      })
      .catch(() => {

      })
}

/**
 * 下载pdf到本地
 */
const downloadPDF = () => {
  if(validatenull(newPdfUrl.value)){
    newPdfUrl.value = sealSignForm.value.signFilePath
  }
  //通过阿里云oss提供的下载接口获取下载地址
  let filename = newPdfUrl.value.split(".com/")[1]
  const response = {
    'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
  }
  const url = proxy.$OSS.signatureUrl(filename, { response });

  try {
    let elemIF = document.createElement("iframe");
    elemIF.src = url;
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);
  } catch (e) {
    alert("下载异常！");
  }
}

/**
 * 撤回签署文件
 */
const withdraw = () => {
  ElMessageBox.confirm(
      '确认撤回该签署任务吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        withdrawSignApi(signId.value)
            .then(res=>{
              let data = res.data.result
              if(data === "success"){
                ElMessage.success("撤回成功！")
                proxy.$router.push("/sign-con")
              }else {
                ElMessage.error("撤回失败，请重试！")
              }
            }).catch(res=>{
          ElMessage.error(res.data.error)
        })
      })
      .catch(() => {

      })
}

</script>

<style scoped>
/deep/ .vue-pdf__wrapper {
  position: relative;
  margin-left: 80px;
}
/deep/ .ivu-icon{
  padding-right: 4px;
}

/deep/ .el-button--primary{
  color: #fff;
  background-color: #1063f1;
  border-color: #1063f1;
  font-weight: normal;
}
/deep/ .el-button--primary:hover{
  background-color: #0082FF;
  border-color: #0082FF;
}
/deep/ .el-button--danger{
  background-color: transparent;
  border-color: transparent;
  font-weight: normal;
  margin-right: 10px;
}
/deep/ .el-button--danger:hover{
  color: #0082FF;
}


/deep/ .el-divider--horizontal{
  margin: 0;
}
/deep/ .el-timeline-item__node--large{
  width: 20px;
  height: 20px;
}


/deep/ .el-button--info{
  width: 160px;
  margin: 0 20px;
  color: #fff;
  background-color: #1063f1;
  border-color: #1063f1;
}
/deep/ .el-button--info:hover{
  background-color: #0082FF;
  border-color: #0082FF;
}

/deep/ .el-button--info.is-plain{
  width: 160px;
  margin: 0;
  color: #606266;
  background-color: #fff;
  border-color: #fff;
}
/deep/ .el-button--info.is-plain:hover{
  background-color: #ecf5ff;
  border-color: #ecf5ff;
  color: #1063f1;
}
/deep/ .el-tabs__item.is-active{
  color: #1063f1;
}
/deep/ .el-tabs__active-bar{
  background-color: #1063f1;
}
/deep/ .el-tabs__item:hover{
  color: #1063f1;
}


</style>
